package indi.zhifa.study2024.nbr.logic.curd.account.impl;

import indi.zhifa.core.common.web.entity.exception.ServiceException;
import indi.zhifa.core.mpenhance.utils.DbDtoEntityUtil;
import indi.zhifa.study2024.nbr.gen.busy.domain.mapper.GenDomainMapper;
import indi.zhifa.study2024.nbr.gen.busy.domain.po.GenDomainEntity;
import indi.zhifa.study2024.nbr.gen.busy.domain.service.IGenDomainDbService;
import indi.zhifa.study2024.nbr.gen.busy.user.po.GenBusyUserEntity;
import indi.zhifa.study2024.nbr.gen.busy.user.po.json.DomainInfo;
import indi.zhifa.study2024.nbr.gen.busy.user.service.IGenBusyUserDbService;
import indi.zhifa.study2024.nbr.logic.curd.account.IDomainAssignService;
import indi.zhifa.study2024.nbr.logic.curd.account.entity.request.AssignDomainRequest;
import indi.zhifa.study2024.nbr.logic.curd.account.entity.response.AssignDomainResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Component
public class DomainAssignServiceImpl implements IDomainAssignService {

    final IGenDomainDbService mDomainDbService;
    final IGenBusyUserDbService mUserDbService;

    @Override
    public AssignDomainResponse assignDomain(Long pUserId, AssignDomainRequest request) {

        GenBusyUserEntity userEntity = mUserDbService.getById(pUserId);
        if(null == userEntity) {
            throw new ServiceException("您的公司下没有找到Id为"+pUserId+"的用户");
        }
        List<GenDomainEntity> domainEntityList = mDomainDbService.listByCascadeCode(request.getCascadeCodes());
        List<DomainInfo> domainInfos = domainEntityList.stream().map(domainEntity->{
            DomainInfo domainInfo = new DomainInfo();
            domainInfo.setId(domainEntity.getId());
            domainInfo.setName(domainEntity.getName());
            domainInfo.setCode(domainEntity.getCode());
            domainInfo.setCascadeCode(domainEntity.getCascadeCode());
            return domainInfo;
        }).toList();
        userEntity.setDomains(domainInfos);
        mUserDbService.updateById(userEntity);
        AssignDomainResponse rtn = DbDtoEntityUtil.trans(userEntity, AssignDomainResponse.class);
        return rtn;
    }
}
